<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Site;
use Auth;
use App\Http\Requests\SiteRequest;
use App\Models\User;
class SitesController extends Controller
{


    public function __construct()
    {
        $this->middleware('auth');
    }

    public function index(Request $request, Site $site, User $member = null)
    {
        $user = Auth::user();

        $query = Site::with('user');
        if ($member && $user->hasRole('Founder')) {
            $query->where('user_id', $member->id)->orderBy('updated_at', 'desc');
        } else if ($user->hasRole('Founder')){
            $query->orderBy('updated_at', 'desc');
        } else {
            $query->where('user_id', $user->id)->orderBy('updated_at', 'desc');
        }
        $sites = $query->filter($request->all())->paginate(20);
        return view('sites.index', compact('user', 'sites'));
    }

    public function create(Site $site, Request $request)
    {
        $user = Auth::user();
        return view('sites.create', compact('user'));
    }

    public function store(Site $site, SiteRequest $request)
    {
        $site->fill($request->all());
        $site->user_id = Auth::id();
        $site->save();

        return redirect()->route('sites.edit', $site->id)->with('success', '添加成功！');
    }
    public function show(Site $site)
    {
        $user = Auth::user();
        return view('sites.show', compact('user', 'site'));
    }
    public function edit(Site $site)
    {
        $this->authorize('destroy', $site);
        $user = Auth::user();
        $site = Site::with(['ads' => function ($query) {
            $query->orderBy('id', 'asc');
        }])->find($site->id);
        return view('sites.edit', compact('user', 'site'));
    }

    public function update(Site $site, SiteRequest $request)
    {
        $this->authorize('destroy', $site);

        $site->update($request->all());

        return redirect()->route('sites.edit', $site->id)->with('success', '更新成功！');
    }

    public function destroy(Site $site)
    {
        $this->authorize('destroy', $site);
        $site->delete();

        return redirect()->route('sites.index')->with('success', '成功删除站点！');
    }

    public function short_url(Site $site)
    {
        $this->authorize('destroy', $site);

        return view('sites.short_url', compact('user', 'site'));
        //return redirect()->route('sites.index')->with('success', '')
    }
}
